﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DispatchAssist.BusinessLogical.BLL;
using DispatchAssist.BusinessLogical.Model;
using CarolLib.WinService;
using System.Text.RegularExpressions;
using CarolLib;
using DispatchAssist.Model;

namespace DispatchAssist.MessageBodyGenerator
{
    public class Generator:IBasicTask
    {
        #region members

        static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private static MessageCreateManger manger ; 

        #endregion

        #region IBasicTask
        public void Init()
        {
            manger = new MessageCreateManger();
        }

        public void Execute()
        {
            //step1.获取需要生成arcars报文的预警相关信息

            List<AlertAllInfo> sourceList;
            try
            {
                sourceList = manger.GetNecessaryAlertInfo(Enums.AlertActionFlag.AutoSendAcarsAlert|Enums.AlertActionFlag.ConfirmAcars,Enums.AlertActionFlag.AutoSendAcarsAlert);
      
            }
            catch (Exception e)
            {
                Logger.Error("error in GetNecessaryAlertInfo",e);
                return;
            }

            if (sourceList == null || sourceList.Count == 0)
            {
                Logger.Info("there is no new alert message");
                return;
            }

            List<AlertAllInfo> successList = new List<AlertAllInfo>();

            foreach (AlertAllInfo source in sourceList)
            {
                //step2.获取模板信息

                List<int> actions=SplitActionFlag(source.AlertActionFlag,source.PerformActionFlag);


                source.PerformActionFlag = 0;

                foreach(int action in actions)
                {
                    MsgTemplate templateInfo;
                    try
                    {
                        templateInfo = GetTempleteInfo(source.TailNo, action);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(string.Format("error in get template info,actionFlag is {0},TailNo is {1}",action, source.TailNo), e);

                        continue;
                    }

                    //3.组装消息实体

                    ACARSMsg msg = new ACARSMsg();

                    msg.AlertID = source.AlertID;
                    msg.ReceiveTailNo = source.TailNo;
                    try
                    {
                        msg.MsgBody = MessageBodyFactory.GetMessageBody<AlertAllInfo>(source, templateInfo.MsgContent);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(string.Format("error in get message body template id is {0},AlertID is {1}",templateInfo.MsgTemplateID,source.AlertID),e);

                        continue;
                    }
                    msg.MsgStatus =(int) Enums.MessageStatus.FinishCreate;

                    try
                    { 
                        manger.InsertACARSMsgModel(msg);

                        source.PerformActionFlag = source.PerformActionFlag | (action==((int)(Enums.AlertActionFlag.AutoSendAcarsAlert|Enums.AlertActionFlag.ConfirmAcars))?(int)Enums.AlertActionFlag.AutoSendAcarsAlert:action);

                        if (!successList.Contains(source))
                        {
                            successList.Add(source);
                        }
                       
                    }
                    catch(Exception e)
                    {
                        Logger.Error("error in Insert Arcars Message Data", e);
                        continue;
                    }

                }

            }

            //4. 将消息加入队列并更新Alert状态

            try
            {
                manger.UpdateAlertStatus(successList);
            }
            catch (Exception e)
            {
                Logger.Error("error in update Status",e);
            }

        }

       

        public void Exit()
        {

        }
        #endregion


        #region private method
        private MsgTemplate GetTempleteInfo(string tailNo, int actionFlag)
        {

            string deviceType=null;
            try
            {
               // deviceType = manger.GetDeviceModel(tailNo).ACARSType;

                deviceType = CommonCacheData.CacheACARDevice.GetACARSDeviceByPara(tailNo).ACARSType;
            }
            catch(Exception e)
            {
                Logger.Error("get ARACRS Type error ,tailNO is "+tailNo,e);
            }
            //return manger.GetMsgTemplate(null, actionFlag, deviceType);

            return CommonCacheData.CacheTemplate.GetTemplateByPara(actionFlag, deviceType);
        }

        private List<int> SplitActionFlag(int allActions,int performActions)
        {
            List<int> result = new List<int>();

            if ((allActions | ((int)Enums.AlertActionFlag.AutoSendAcarsAlert|(int)Enums.AlertActionFlag.ConfirmAcars)) == allActions && ((performActions&(int)Enums.AlertActionFlag.AutoSendAcarsAlert) ==0))
            {
                result.Add((int)Enums.AlertActionFlag.AutoSendAcarsAlert|(int)Enums.AlertActionFlag.ConfirmAcars);
            }
            //if ((allActions | (int)Enums.AlertActionFlag.ManualSendAcrarsAlert) == allActions && ((performActions & (int)Enums.AlertActionFlag.ManualSendAcrarsAlert) == 0))
            //{
            //    result.Add((int)Enums.AlertActionFlag.ManualSendAcrarsAlert);
            //}

            return result;
        }

        #endregion
    }
}
